package com.njdf.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

public class IPFilter implements Filter {
    private ServletContext context;

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String ip = req.getRemoteAddr();
        Map<String, Integer> ipCountMap = (Map<String, Integer>) context .getAttribute("ipCountMap");
        Integer count = ipCountMap.get(ip);
        if (count == null) {
            count = 1;
        } else {
            count += 1;
        }
        ipCountMap.put(ip, count);
        context.setAttribute("ipCountMap", ipCountMap);
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        context = config.getServletContext();
        Map<String, Integer> ipCountMap = Collections.synchronizedMap(new LinkedHashMap<String, Integer>());
        context.setAttribute("ipCountMap", ipCountMap);
    }

}
